package com.erp.pro.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.erp.common.controller.BaseController;
import com.erp.common.domain.DictDO;
import com.erp.common.service.DictService;
import com.erp.common.utils.*;
import com.erp.itm.domain.ProjectDO;
import com.erp.pro.domain.*;
import com.erp.pro.service.ProductLogService;
import com.erp.pro.service.ProductQtyService;
import com.erp.system.domain.UserDO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.erp.pro.service.ProductService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 产品列表
 * 
 * @author Eric
 * @email shiliang900713@163.com
 * @date 2019-07-01 15:42:37
 */
 
@Controller
@RequestMapping("/pro/product")
public class ProductController  extends BaseController {
	@Autowired
	private ProductService productService;

	@Autowired
	private DictService dictService;

	@Autowired
	private ProductLogService productLogService;

	@Autowired
	private ProductQtyService productQtyService;

	@GetMapping()
	String Product(){
	    return "pro/product/product";
	}
	
	@ResponseBody
	@GetMapping("/list")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<ProductDO> productList = productService.list(query);
		int total = productService.count(query);
		PageUtils pageUtils = new PageUtils(productList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("pro:product:add")
	String add(){
	    return "pro/product/add";
	}

	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Long id,Model model){
		ProductDO product = productService.get(id);
		List<DictDO> dictDOS = dictService.listByType("pro_status");
		String type = product.getStatus();
		for (DictDO dictDO:dictDOS){
			if(type.equals(dictDO.getValue())){
				dictDO.setRemarks("checked");
			}
		}
		model.addAttribute("prostatus",dictDOS);
		model.addAttribute("product", product);
	    return "pro/product/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	public R save( ProductDO product){
		setsavproinfo(product);
		if(productService.save(product)>0){
			//记录日志
			ProductLogDO productLogDO = new ProductLogDO();
			productLogDO.setProId(product.getId());
			productLogDO.setSku(product.getSku());
			productLogDO.setGmtCreate(new Date());
			productLogDO.setUserNameCreate(getUsername());
			productLogDO.setUserIdCreate(getUserId());
			productLogDO.setRemarks("新增产品["+product.getSku()+"]");
			productLogService.save(productLogDO);
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	public R update( ProductDO product){
		ProductDO productDO = productService.get(product.getId());
		product.setOnPurQty(productDO.getOnPurQty());
		product.setNTaxPrice(productDO.getNTaxPrice());
		String updateDescr="";
		try{
			Map<String, String> supplierupdate = GetDifference.getObject(productDO, product);
			for(Map.Entry<String, String> entry : supplierupdate.entrySet()){
				updateDescr = updateDescr+"修改["+entry.getKey()+"]为["+entry.getValue()+"]";
				System.out.println("修改前 :" + entry.getKey());
				System.out.println("修改后 :" + entry.getValue());
			}
		}catch (Exception e){
			updateDescr = "记录修改描述异常";
		}
		UserDO current = ShiroUtils.getUser();
		product.setUserIdModified(current.getUserId());
		product.setUserNameModified(current.getName());
		product.setGmtModified(new Date());
		product.setNTaxPrice(calNtaxtPrice(product.getTaxProce(),product.getTaxRate()));
		//记录日志
		ProductLogDO productLogDO = new ProductLogDO();
		productLogDO.setProId(product.getId());
		productLogDO.setSku(product.getSku());
		productLogDO.setGmtCreate(new Date());
		productLogDO.setUserNameCreate(current.getName());
		productLogDO.setUserIdCreate(current.getUserId());
		productLogDO.setRemarks(updateDescr);
		productLogService.save(productLogDO);
		productService.update(product);
		return R.ok();
	}

	/**
	 * 计算不含税价格
	 * @param taxprice
	 * @param taxRate
	 * @return
	 */
	private BigDecimal calNtaxtPrice(BigDecimal taxprice,BigDecimal taxRate){
		BigDecimal ntaxPrice = new BigDecimal(0);
		if(taxprice !=  null){
			if(taxRate != null){
				ntaxPrice = taxprice.multiply(taxRate);
			}else{
				ntaxPrice = taxprice;
			}
		}
		return ntaxPrice;
	}


	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	public R remove( Long id){
		if(productService.remove(id)>0){
			return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	public R remove(@RequestParam("ids[]") Long[] ids){
		productService.batchRemove(ids);
		return R.ok();
	}


	@PostMapping("/getsku")
	@ResponseBody
	ProductDO getsku(@RequestParam Map<String, Object> params) {
		// 存在，返回对象，不存在 返回空
		return productService.getsku(params);
	}
	@GetMapping("/edittab/{id}")
	String edittab(@PathVariable("id") Long id,Model model){
		model.addAttribute("productid",id);
		model.addAttribute("firstsrc","/pro/product/edit/"+id);
		return "pro/product/edittab";
	}

	@PostMapping("/exportData")
	@ResponseBody
	public void downloadTemplate(ProductDO productDO, HttpServletResponse response){
		//ProjectDO project
		Map<String, Object> params = new HashMap<>();
		if(productDO.getIsqty() !=null){
			params.put("isqty",productDO.getIsqty());
		}
		if(productDO.getStatus() != null){
			params.put("statuse",productDO.getStatus());
		}
		if(productDO.getProBrand() != null){
			params.put("proBrand",productDO.getProBrand());
		}
		if(productDO.getProModel() != null){
			params.put("proModel",productDO.getProModel());
		}
		if(productDO.getName() != null){
			params.put("name",productDO.getName());
		}
		List<ProductDO> productList = productService.list(params);
		ExcelUtil.exportExcel(productList,"产品信息","产品信息",ProductDO.class,"产品信息.xls",response);
	}



	@GetMapping("/getProBrand")
	@ResponseBody
	List<String> getProBrand() {
		return productService.getProBrand();
	}

	@GetMapping("/importexcel")
	String importexcel(){
		return "pro/product/importexcel";
	}

	@GetMapping("/downloadTemplate")
	@ResponseBody
	void downloadTemplate(HttpServletResponse response){
		List<ProductDO> productDOList = new ArrayList<>();
		ExcelUtil.exportExcel(productDOList,"商品模板","商品模板",ProductDO.class,"商品模板.xls",response);
	}

	@PostMapping("/importInfo")
	public String importInfo(@RequestParam("file") MultipartFile file) {
		ImportParams importParams = new ImportParams();
		// 数据处理
		importParams.setHeadRows(1);
		importParams.setTitleRows(1);
		// 需要验证
		importParams.setNeedVerfiy(false);
		int errorcount = 0;
		int successcount = 0;
		try{
			ExcelImportResult<ProductDO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), ProductDO.class,
					importParams);
			List<ProductDO> productDOList = result.getList();
			if(productDOList != null && productDOList.size()>0){
				for (ProductDO product:productDOList) {
					if(StringUtils.isNotBlank(product.getSku())){
						//判断SKU是否已经存在
						ProductDO entity = productService.getskuinfo(product.getSku());
						if(entity != null ){
							errorcount ++;
							System.out.println("SKU以已经存在");
						}else{
							setsavproinfo(product);
							if(productService.save(product)>0){
								//记录日志
								ProductLogDO productLogDO = new ProductLogDO();
								productLogDO.setProId(product.getId());
								productLogDO.setSku(product.getSku());
								productLogDO.setGmtCreate(new Date());
								productLogDO.setUserNameCreate(getUsername());
								productLogDO.setUserIdCreate(getUserId());
								productLogDO.setRemarks("批量新增产品["+product.getSku()+"]");
								productLogService.save(productLogDO);
							}
							successcount ++;
						}
					}else{
						errorcount ++;
						System.out.println("SKU不存在");
					}
				}
			}else{
				errorcount ++;
				System.out.println("表格为空");
			}
			return "导入完成：导入成功"+successcount+"条，失败"+errorcount+"条";
		}catch (IOException e) {
			System.out.println(e.getMessage());
			return "e:导入失败";
		} catch (Exception e1) {
			e1.printStackTrace();
			System.out.println(e1.getMessage());
			return "e1:导入失败";
		}
	}

	private void setsavproinfo(ProductDO product) {
		product.setUserIdCreate(getUserId());
		product.setUserNameCreate(getUsername());
		product.setGmtCreate(new Date());
		product.setUserIdModified(getUserId());
		product.setUserNameModified(getUsername());
		product.setGmtModified(new Date());
		product.setNTaxPrice(calNtaxtPrice(product.getTaxProce(), product.getTaxRate()));
		product.setOnPurQty(0);
		product.setAllQty(0);
		product.setStatus("1");
	}

}
